package com.spj.shiro_mvc;

import com.spj.entity.User;
import com.spj.service.impl.UserServiceDaoImpl;
import io.jsonwebtoken.Jwt;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * @author :spj
 * @Date:2022/4/14
 * @description:
 */
@Configuration
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserServiceDaoImpl service;
    @Override
    public boolean supports(AuthenticationToken token) {
//        这里是shiro底层的问题，我们要手动重写底层的判断逻辑
        return token instanceof MyJWT;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String token = principals.getPrimaryPrincipal()+"";
        String username = JwtUtil.getSubject(token);
        //检验后
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        //添加信息
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken jwtToken) throws AuthenticationException {
        String token = jwtToken.getPrincipal()+"";
        String username = JwtUtil.getSubject(token);
        User user=service.login(username);
        String password=Integer.toString(user.getAge());
        JwtUtil.verify(token,username,password);
        return new SimpleAuthenticationInfo(token,token,"myRealm");
    }
}
